package com.augrain.microframework.core.util;

import lombok.extern.slf4j.Slf4j;

import java.lang.management.ManagementFactory;
import java.lang.management.MemoryMXBean;
import java.lang.management.MemoryUsage;

/**
 * SysUtils工具类
 *
 * @author biaoy
 * @since 2024/12/27
 */
@Slf4j
public class SysUtils {

    private static final String OS_NAME = System.getProperty("os.name");
    private static String pidCache = null;
    private static boolean isLinuxPlatform = false;
    private static boolean isWindowsPlatform = false;

    static {
        if (OS_NAME != null && OS_NAME.toLowerCase().contains("linux")) {
            isLinuxPlatform = true;
        }

        if (OS_NAME != null && OS_NAME.toLowerCase().contains("windows")) {
            isWindowsPlatform = true;
        }
    }

    private SysUtils() {

    }

    public static boolean isWin() {
        return isWindowsPlatform;
    }

    public static boolean isLinuxPlatform() {
        return isLinuxPlatform;
    }

    public static long getMxMemory() {
        return Runtime.getRuntime().maxMemory();
    }

    public static boolean isClassPresent(String className) {
        try {
            Class.forName(className);
            return true;
        } catch (IllegalAccessError err) {
            throw new IllegalStateException("Readability mismatch in inheritance hierarchy of class [" +
                    className + "]: " + err.getMessage(), err);
        } catch (Throwable ex) {
            // Typically ClassNotFoundException or NoClassDefFoundError...
            return false;
        }
    }

    public static void printMemory() {
        // 获取 MemoryMXBean 对象
        MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean();

        // 获取堆内存使用情况
        MemoryUsage heapMemoryUsage = memoryMXBean.getHeapMemoryUsage();

        // 打印堆内存信息
        log.info("Heap Memory Usage:");
        log.info("  Initial Memory: {}", formatMemorySize(heapMemoryUsage.getInit()));
        log.info("  Used Memory: {}", formatMemorySize(heapMemoryUsage.getUsed()));
        log.info("  Committed Memory: {}", formatMemorySize(heapMemoryUsage.getCommitted()));
        log.info("  Max Memory: {}", formatMemorySize(heapMemoryUsage.getMax()));
    }

    public static String formatMemorySize(long bytes) {
        if (bytes < 1024) {
            return bytes + " B";
        }
        int exp = (int) (Math.log(bytes) / Math.log(1024));
        char unit = "KMGTPE".charAt(exp - 1);
        return String.format("%.2f %sB", bytes / Math.pow(1024, exp), unit);
    }

    /**
     * 获取进程号
     */
    public static String getPid() {
        if (pidCache == null) {
            String name = ManagementFactory.getRuntimeMXBean().getName();
            pidCache = name.split("@")[0];
        }
        return pidCache;
    }

    /**
     * 获取CPU核心数
     *
     * @return 返回CPU核心数
     */
    public static int getCores() {
        return Runtime.getRuntime().availableProcessors();
    }
}
